package com.mall.order.services;

import com.mall.order.OrderCoreService;
import com.mall.order.biz.TransOutboundInvoker;
import com.mall.order.biz.context.AbsTransHandlerContext;
import com.mall.order.biz.factory.OrderProcessPipelineFactory;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.OrderShipping;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.shopping.constants.ShoppingRetCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * ciggar
 * create-date: 2019/7/30-上午10:05
 */
@Slf4j
@Component
@Service(cluster = "failfast")
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            request.requestCheck();
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);
            System.out.println("consumer");
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 取消订单
     *
     * @param request
     * @return
     */
    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        String orderId = request.getOrderId();
        CancelOrderResponse response = new CancelOrderResponse();
        try {
            //更新order状态
            Order order = new Order();
            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            order.setOrderId(orderId);
            orderMapper.updateByPrimaryKeySelective(order);

            //更新orderItem
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
            for (OrderItem orderItem : orderItems) {
                if (orderItem.getStatus() == 1) {
                    orderItem.setStatus(2);
                    orderItemMapper.updateByPrimaryKeySelective(orderItem);
                    Long itemId = orderItem.getItemId();
                    Integer num = orderItem.getNum();
                    Stock stock = new Stock();
                    stock.setItemId(itemId);
                    stock.setLockCount(-num);
                    stock.setStockCount((long) num);
                    stockMapper.updateStock(stock);
                }
                response.setCode(OrderRetCode.SUCCESS.getCode());
                response.setMsg(OrderRetCode.SUCCESS.getMessage());
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            log.info(e.getMessage());
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            return response;
        }
        return response;
    }

    @Override
    public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest payOrderSuccessRequest) {
        payOrderSuccessRequest.requestCheck();

        String orderId = payOrderSuccessRequest.getOrderId();
        Example orderItemExample = new Example(OrderItem.class);
        orderItemExample.createCriteria().andEqualTo("orderId", orderId);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);
        BigDecimal payment = new BigDecimal(0);
        for (OrderItem orderItem : orderItems) {
            Integer num = orderItem.getNum();
            Double price = orderItem.getPrice();
            payment = payment.add(new BigDecimal(num * price));
        }

        Order order = new Order();
        order.setOrderId(orderId);
        order.setPayment(payment);
        // 在线支付
        order.setPaymentType(1);
        // 邮费 0
        order.setPostFee(new BigDecimal(0));
        // 已付款
        order.setStatus(1);

        Date date = new Date();
        order.setUpdateTime(date);
        order.setPaymentTime(date);

        int updateCount = orderMapper.updateByPrimaryKeySelective(order);
        PayOrderSuccessResponse payOrderSuccessResponse = new PayOrderSuccessResponse();

        if (updateCount == 1) {
            payOrderSuccessResponse.setCode(OrderRetCode.SUCCESS.getCode());
            payOrderSuccessResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
            return payOrderSuccessResponse;
        }
        payOrderSuccessResponse.setCode(OrderRetCode.DB_EXCEPTION.getCode());
        payOrderSuccessResponse.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
        return payOrderSuccessResponse;
    }

    @Override
    public UpdateStockLockCountResponse updateStockLockCount(UpdateStockLockCountRequest updateStockLockCountRequest) {
        updateStockLockCountRequest.requestCheck();
        UpdateStockLockCountResponse response = new UpdateStockLockCountResponse();

        String itemId = updateStockLockCountRequest.getItemId();
        int num = updateStockLockCountRequest.getNum();

        Stock stock = new Stock();
        stock.setItemId(Long.parseLong(itemId));
        stock.setLockCount(-num);
        stock.setStockCount(0L);
//        Example example = new Example(Stock.class);
//        example.createCriteria().andEqualTo("itemId")
        try {
            int updateStock = stockMapper.updateStock(stock);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
            return response;
        } catch (Exception e) {
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
            return response;
        }
//        Stock stockSelected = stockMapper.selectByPrimaryKey(itemId);
//        int lockCount = stockSelected.getLockCount();
//        if (lockCount >= num) {
//            stock.setLockCount(lockCount - num);
//            int update = stockMapper.updateByPrimaryKeySelective(stock);
//            if (update == 1) {
//                response.setCode(OrderRetCode.SUCCESS.getCode());
//                response.setMsg(OrderRetCode.SUCCESS.getMessage());
//                return response;
//            }
//        }


    }

    /**
     * 删除订单
     *
     * @param orderId
     * @return
     */
    @Override
    public DeleteOrderResponse deleteOrder(String orderId) {
        DeleteOrderResponse response = new DeleteOrderResponse();
        try {
            Example shippingExample = new Example(OrderShipping.class);
            shippingExample.createCriteria().andEqualTo("orderId", orderId);
            orderShippingMapper.deleteByExample(shippingExample);
            Example itemExample = new Example(OrderItem.class);
            itemExample.createCriteria().andEqualTo("orderId", orderId);
            orderItemMapper.deleteByExample(itemExample);
            orderMapper.deleteByPrimaryKey(orderId);
            response.setCode(ShoppingRetCode.SUCCESS.getCode());
            response.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.info(e.getMessage());
            response.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            return response;
        }
        return response;
    }

}
